<?php
namespace app\gym\model;
use app\common\model\Base;
use think\Model;
use think\Cache;
use app\gym\model\MemberSigning as membersigning;
/**
*健身房与教练的解约
*健身房签约的逻辑关系
*
*/
class FitnessTrainerSigning extends Base{
    protected $table = 'gym_sign_gym';
    protected static  $cacheTag='fitness_signing'; //缓存的名称,关闭使用缓存直接使用false
    protected static $maxSigning = 1;
    protected static $defaultGym = '';
    protected static  $autoPushCreateTime = true; //自动添加时间
    protected static  $autoPushUpdateTime = true; //自动添加修改时间
    //模型初始化
    //静态查询方法会产生4次实例化的过程
    public function initialize(){
      //直接运行静态的初始化方法
      self::init();
    }

    public static function init(){
      //获取配置文件，并且设置教练最多可以签约多少个健身房
      self::$maxSigning = config('signing.max_fitness_trainer_signing');
      //设置默认的健身房编号
      self::$defaultGym = config('signing.default_gym_id');
    }

    /**
    *教练和健身房进行签约
    *@param $gymcode 健身房的id
    *@param $filtnessTraniner 健身教练的唯一标识 也就是uuid
    */
    public static function signing(){
        $input = self::getInputData();
        //首先确认和默认的健身房进行签约
        if(empty($input['gym_id'])){
            //尝试与默认的健身房进行签约
            if(!self::defaultGymSigin()){

                abort(-0023,'签约失败，健身房的编号不存在！');

            }
            return true;
        }
        //与新的健身房进行签约
        self::couSave(
          [
            ['gym_id','require','健身房的编号不能为空！'],
            [ 'fitness_instructor_id',
              'require|signing_of|signing_max',
              '教练:的编号不能为空!|已经签约了此健身房！|超出最大签约数量!'
            ],
          ]
          ,function($input,$self){
              //获取教练签约健身房的列表
              $list = self::fitnessGymList($input['fitness_instructor_id']);
              $gymList = array_column($list,'gym_id');
              $dataObj = new $self();
              $where = ['fitness_instructor_id'=>$input['fitness_instructor_id']];
              //如果进行签约的是默认的健身房的话
              if(self::$defaultGym == $input['gym_id']){
                  $where = ['fitness_instructor_id'=>$input['fitness_instructor_id'],'gym_id'=>$input['gym_id'],'status'=>0];
                  $sqlResult =function($where){
                    return self::where($where);
                  };
                  //如果签约过默认的健身房并且解约的话那么就再次和默认的健身房进行签约
                  if($sqlResult($where)->count() > 0){
                    return $dataObj->allowField(true)->save(['status'=>1],$where);
                  }
              }
              if(in_array(self::$defaultGym,$gymList)){
                    //如果存在默认的健身房进行默认的健身房的转移操作
                    //检查教练下面的会员数量
                    $memberSigning = membersigning::fitnessGymMebers(['fitness_instructor_id'=>$input['fitness_instructor_id'],'gym_id'=>self::$defaultGym]);
                    $memberSIgningColumn = array_column($memberSigning,'member_id');
                    $circle = db('circle')->where(['uuid'=>['in',$memberSIgningColumn]])->update(['gym_id'=>$input['gym_id']]);
                    $course = db('course')->where(['member_id'=>['in',$memberSIgningColumn]])->update(['gym_id'=>$input['gym_id']]);
                    $hourCourse = db('hour_course')->where(['member_id'=>['in',$memberSIgningColumn]])->update(['gym_id'=>$input['gym_id']]);
                    $reservationCourse = db('reservation_course')->where(['reservation_person_id'=>['in',$memberSIgningColumn]])->update(['gym_id'=>$input['gym_id']]);
                    db('signing_fitness_instructor')->where(['member_id'=>['in',$memberSIgningColumn]])->update(['gym_id'=>$input['gym_id']]);
                    return $dataObj->allowField(true)->save(['gym_id'=>$input['gym_id']],$where);
              }
              //增加健身房簽約教練的記錄
              return $dataObj->data($input)->allowField(true)->isUpdate(false)->save();
          }
        );
        return [];
    }


    protected static function validateExtend($validate){
          //运行父类别的方法
          parent::validateExtend($validate);
          $validate->extend(
            [
              'signing_of'=>function($val){
                 $return = true;
                 $fitnessSigning = '\\app\\gym\\model\\FitnessTrainerSigning';
                 $input = $fitnessSigning::getInputData();
                 $list = $fitnessSigning::fitnessGymList($val);
                 $gymList = array_column($list,'gym_id');
                 if(in_array($input['gym_id'],$gymList)){
                    $return = false;
                 }
                 return $return;
              },
              //查询健身房和教练是否已经签约
                'signing_of_desc'=>function($val){
                    $return = false;
                    $fitnessSigning = '\\app\\gym\\model\\FitnessTrainerSigning';
                    $input = $fitnessSigning::getInputData();
                    $list = $fitnessSigning::fitnessGymList($val);
                    $gymList = array_column($list,'gym_id');
                    if(in_array($input['gym_id'],$gymList)){
                        $return = true;
                    }
                    return $return;
                },
              //教练的签约是否超过最大的签约数量
              'signing_max'=>function($val){
                  $return = true;
                  $list = \app\gym\model\FitnessTrainerSigning::fitnessGymList($val);
                  $gymList = array_column($list,'gym_id');
                  $maxSigning = config('signing.max_fitness_trainer_signing'); //教练与健身房的最大的签约数量
                  $defaultGym = config('signing.default_gym_id'); //系统默认的健身房
                  if(count($gymList) >= $maxSigning && !in_array($defaultGym,$gymList)){
                        $return  = false;
                  }
                  return $return;
              }
            ]
          );
    }


    /**
     * [defaultGymSigin 教练与系统默认的健身房进行签约]
     * @return [type] [返回签约的内容]
     */
    protected static function defaultGymSigin(){
        //首先确定教练和健身房的签约的数量和状态
        $inputData = self::getInputData();
        $siginList = self::fitnessGymList($inputData['fitness_id']);
        if(!empty($siginList) && isset($siginList)){
            return false; //代表已经存在签约的健身房，无需再次进行签约
        }
        return true;
    }


    /**
     * [fitnessGymList 教练目前签约健身房的列表,这个列表中只会展示目前教练签约的健身房并且是还
     * 没有与健身房进行解约的]
     * @param  [type] $fitness [教练的编号]
     * @return [type]          [教练签约健身房的数组]
     */
    protected static function fitnessGymList($fitnessId){
        $where = ['fitness_instructor_id'=>$fitnessId,'status'=>1];
        $field = ['gym_id','create_time','status'];
        $result = self::where($where);
        $response = self::infoOfCache($result);
        return $response;
    }




    /**
    *签约统计
    *统计当前教练签约的健身房数量
    */
    public static function signingCount( $info ){
        $where = ['fitness_instructor_id'=>$info['fitness_instructor_id'],'status'=>1];
        return self::where($where)->count();
    }

    /**
    *健身房与教练的解约
    *@param $filtnessTrainer 教练的解约
    *@param $gymId 健身房解约
    */
    public static function unSigning($gymcode=null,$filtnessTrainer=null){



    }


    /**
    *教练和健身房签约查询
    *此个方法有两种模式;
    *1.设置教练最多可以签约几个健身房
    */
    public function info(){

    }




    /**
    *@param 教练的uuid
    */
    public static function fitnessTrainerSignSum($filtnessTrainer=null){


    }


    /**
    *查询教练的签约信息
    *查询教练的签约信息
    */
    public static function ffitnessTrainerSignInfo($filtnessTrainer=null){

    }

    /**
    *查询教练签约的健身房的数量
    */
    public static function signingSum($member){

    }

    /**
     * [seeMembers 查询当前教练签约的会员列表]
     * @return [array] [返回数组的内容]
     */
    public static function infoMembers($fitnessId=null){
        if(empty($fitnessId)){
            abort(-0030,'教练的id不能是空的！');
        }
        $where = ['fitness_instructor_id'=>$fitnessId];
        $response = self::infoOfCache(self::where($where)->select());
        return $response;
    }

    /**
     * [fitnessCount 健身房下面的教练的数量统计]
     * @return [type] [description]
     */
    public static function gymFitnessCount($info=[]){
        if(array_key_exists('gym_id',$info)){
          $where = is_array($info['gym_id'])? ['gym_id'=>['in',$info['gym_id']]]:['gym_id'=>$info['gym_id']];
        }else{
          abort(-20,'参数错误！');
        }
        $result = self::where($where);
        $result->where(['status'=>1]);
        return $result->count();
    }


    /**
     * [gymFitnessSigningInfo 查询教练当前归属的健身房信息]
     * @param  array  $info [description]
     * @return [type]       [description]
     */
    public static function gymFitnessSigningInfo($info=[]){
         $where = ['fts.fitness_instructor_id'=>$info['fitness_id'],'fts.status'=>1];
         $result = self::where($where)->alias('fts')->join('__GYM_INFO__ gi','fts.gym_id = gi.unique_id','INNER');
         $response = self::infoOfCache($result);
         return $response;
    }


    /**
     * 教练与健身房进行解约
    */
    public static function unFitnessByGmySign(){

        self::couSave(
            [
             ['fitness_instructor_id','require|signing_of_desc',' :教练的编号不能为空！| 当前教练并没有与当前健身房签约'],
             ['gym_id','require','健身房的编号不能为空！']
            ],
        function($input,$self){
                $dataObj = new $self();
                $where = [
                    'fitness_instructor_id'=>$input['fitness_instructor_id'],
                    'gym_id'=>$input['gym_id']
                ];
                //修改当前签约的状态
                return $dataObj->save(['status'=>0],$where);
        });
        return [];
    }

}
